# @Time    :2025/4/7 8:31
"""
3.创建一个迭代器类Mylterator，用于遍历一个给定列表的元素。实现iter和next方法。使用该迭代器类遍历
列表[10,20,30,40],并打印每个元素。
"""


class Mylterator:
    def __init__(self, data):
        self.data = data  # 迭代器容器
        self.index = 0

    def __iter__(self):  # 迭代器协议
        return self

    # def __next__(self):  # 迭代器协议
    #     if self.index < len(self.data):
    #         result = self.data[self.index]#返回当前索引对应的元素
    #         self.index += 1
    #         return result
    #     else:
    #         raise StopIteration
    # 或者这样写
    def __next__(self):  # 迭代器协议
        if self.index >= len(self.data):
            raise StopIteration
        else:
            result = self.data[self.index]  # 返回当前索引对应的元素
            self.index += 1
            return result


# 使用该迭代器类遍历列表[10, 20, 30, 40],并打印每个元素
my_list = [10, 20, 30, 40]
my_iterator = Mylterator(my_list)

for item in my_iterator:
    print(item)

# class Mylterator:
#     def __init__(self, data):
#         self.data = data
#         self.index = 0
#
#     def __iter__(self):  # 迭代器协议
#         return self
#
#
# list1 = [10, 20, 30, 40]
# it = Mylterator(list1)
# for i in it:
#     print(i)
#     it.index += 1
#     if it.index == len(it.data):
#         break
